"""
信息显示格式化工具类
提供统一的信息格式化功能，美化控制台输出
"""

from datetime import datetime
from typing import List, Tuple, Dict, Any


class DisplayFormatter:
    """信息显示格式化器"""
    
    # 图标常量
    ICONS = {
        'success': '✅',
        'error': '❌', 
        'warning': '⚠️',
        'info': '💡',
        'user': '👤',
        'users': '👥',
        'clock': '🕒',
        'calendar': '📅',
        'chart': '📊',
        'document': '📋',
        'search': '🔍',
        'settings': '⚙️',
        'camera': '📷',
        'clock_in': '🟢',
        'clock_out': '🔴',
        'online': '🟢',
        'offline': '🔴',
        'new': '🆕',
        'hot': '🔥'
    }
    
    @staticmethod
    def create_header(title: str, width: int = 60, char: str = '=') -> str:
        """创建标题头部"""
        return char * width + '\n' + f"{title:^{width}}" + '\n' + char * width
    
    @staticmethod
    def create_section_header(title: str, width: int = 50, char: str = '-') -> str:
        """创建章节标题"""
        return f"{title}\n{char * width}"
    
    @staticmethod
    def format_timestamp(dt: datetime = None, format_type: str = 'full') -> str:
        """格式化时间戳"""
        if dt is None:
            dt = datetime.now()
        
        if format_type == 'time':
            return dt.strftime('%H:%M:%S')
        elif format_type == 'date':
            return dt.strftime('%Y-%m-%d')
        elif format_type == 'datetime':
            return dt.strftime('%Y-%m-%d %H:%M:%S')
        else:  # full
            return dt.strftime('%Y-%m-%d %H:%M:%S')
    
    @staticmethod
    def format_time_ago(dt: datetime) -> str:
        """格式化相对时间"""
        now = datetime.now()
        diff = now - dt
        
        if diff.days > 0:
            return f"{diff.days}天前"
        elif diff.seconds > 3600:
            hours = diff.seconds // 3600
            return f"{hours}小时前"
        elif diff.seconds > 60:
            minutes = diff.seconds // 60
            return f"{minutes}分钟前"
        else:
            return "刚刚"
    
    @staticmethod
    def format_list_item(index: int, content: str, icon: str = None) -> str:
        """格式化列表项"""
        prefix = f"{index:2d}."
        if icon:
            prefix += f" {icon}"
        return f"{prefix} {content}"
    
    @staticmethod
    def format_key_value(key: str, value: Any, indent: int = 2) -> str:
        """格式化键值对"""
        spaces = " " * indent
        return f"{spaces}• {key}: {value}"
    
    @staticmethod
    def format_status_line(name: str, status: str, details: str = None, icon: str = None) -> str:
        """格式化状态行"""
        line = f"  {icon + ' ' if icon else ''}{name}: {status}"
        if details:
            line += f" ({details})"
        return line
    
    @staticmethod
    def format_attendance_record(index: int, name: str, action: str, timestamp: str, 
                               time_ago: str = None) -> str:
        """格式化考勤记录"""
        icon = DisplayFormatter.ICONS['clock_in'] if action == 'in' else DisplayFormatter.ICONS['clock_out']
        action_text = '上班' if action == 'in' else '下班'
        
        line = f"{index:2d}. {icon} {name} | {action_text} | {timestamp}"
        if time_ago:
            line += f" ({time_ago})"
        return line
    
    @staticmethod
    def format_person_info(name: str, created_at: str, attendance_info: str = None, 
                          index: int = None) -> List[str]:
        """格式化人员信息"""
        lines = []
        
        # 主信息行
        if index:
            lines.append(f"{index:2d}. {name}")
        else:
            lines.append(f"{DisplayFormatter.ICONS['user']} {name}")
        
        # 录入时间
        try:
            created_time = datetime.strptime(created_at, '%Y-%m-%d %H:%M:%S')
            time_ago = DisplayFormatter.format_time_ago(created_time)
            lines.append(f"    {DisplayFormatter.ICONS['calendar']} 录入时间: {created_at} ({time_ago})")
        except ValueError:
            lines.append(f"    {DisplayFormatter.ICONS['calendar']} 录入时间: {created_at}")
        
        # 考勤信息
        if attendance_info:
            lines.append(f"    {DisplayFormatter.ICONS['chart']} 考勤统计: {attendance_info}")
        
        return lines
    
    @staticmethod
    def format_statistics_summary(total_people: int, today_new: int, week_new: int, 
                                month_new: int) -> List[str]:
        """格式化统计摘要"""
        return [
            f"{DisplayFormatter.ICONS['users']} 总录入人数: {total_people} 人",
            "",
            f"{DisplayFormatter.ICONS['chart']} 录入时间统计:",
            f"  • 今日新增: {today_new} 人",
            f"  • 本周新增: {week_new} 人", 
            f"  • 本月新增: {month_new} 人"
        ]
    
    @staticmethod
    def format_attendance_summary(total_records: int, people_count: int, 
                                clock_in_count: int, clock_out_count: int) -> List[str]:
        """格式化考勤统计摘要"""
        return [
            f"{DisplayFormatter.ICONS['chart']} 总体统计:",
            f"  • 总考勤记录: {total_records} 条",
            f"  • 参与考勤人数: {people_count} 人",
            f"  • 上班打卡: {clock_in_count} 次",
            f"  • 下班打卡: {clock_out_count} 次"
        ]
    
    @staticmethod
    def format_today_attendance(attendance_data: Dict[str, List[Tuple[str, str]]]) -> List[str]:
        """格式化今日考勤情况"""
        lines = [f"{DisplayFormatter.ICONS['calendar']} 今日考勤情况:"]
        
        if not attendance_data:
            lines.append("  ❌ 今日暂无考勤记录")
            return lines
        
        for name, records in attendance_data.items():
            records.sort(key=lambda x: x[1])  # 按时间排序
            
            clock_in_times = [ts for action, ts in records if action == 'in']
            clock_out_times = [ts for action, ts in records if action == 'out']
            
            status_info = []
            if clock_in_times:
                first_in = clock_in_times[0].split(' ')[1]  # 只取时间部分
                status_info.append(f"上班: {first_in}")
            
            if clock_out_times:
                last_out = clock_out_times[-1].split(' ')[1]  # 只取时间部分
                status_info.append(f"下班: {last_out}")
            
            if not clock_out_times and clock_in_times:
                status_info.append(f"{DisplayFormatter.ICONS['offline']} 未下班")
            elif not clock_in_times:
                status_info.append(f"{DisplayFormatter.ICONS['warning']} 仅下班打卡")
            
            lines.append(f"  {DisplayFormatter.ICONS['user']} {name}: {' | '.join(status_info)}")
        
        return lines
    
    @staticmethod
    def create_empty_state_message(message_type: str) -> List[str]:
        """创建空状态消息"""
        messages = {
            'no_faces': [
                f"{DisplayFormatter.ICONS['error']} 暂无已录入人脸的人员",
                f"{DisplayFormatter.ICONS['info']} 提示：请先使用'录入信息'功能添加人员"
            ],
            'no_attendance': [
                f"{DisplayFormatter.ICONS['error']} 暂无考勤记录", 
                f"{DisplayFormatter.ICONS['info']} 提示：请先进行人脸识别并打卡"
            ],
            'cleared': [
                "📝 信息显示区域已清空",
                f"{DisplayFormatter.ICONS['info']} 提示：点击相应按钮查看信息"
            ]
        }
        return messages.get(message_type, [f"{DisplayFormatter.ICONS['info']} {message_type}"])